package follow.juc.heima.day7.Implementthread;

/**
 * 证明同步函数使用的是this锁
 * 思路：一个线程使用同步代码，一个线程使用同步函数，如果使用的不是同一把锁则会发生线程安全的问题
 */
public class SynchronizedDemo implements Runnable {
    private Integer count = 100;
    private boolean flag = true;

    //自定义锁对象
    private Object object = new Object();

    @Override
    public void run() {
        if (flag) {
            while (true) {
                synchronized (object) {
                    if (count > 0) {
                        try {
                            Thread.sleep(40);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        System.out.println(Thread.currentThread().getName() + ",出售第" + (100 - count + 1) + "张票");
                        count--;

                    }
                }
            }
        } else {
            while (true) {
                sale();
            }
        }

    }


    public synchronized void sale() {
        if (count > 0) {
            try {
                Thread.sleep(40);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + ",出售第" + (100 - count + 1) + "张票");
            count--;
        }
    }

    public static void main(String[] args) throws InterruptedException {
        SynchronizedDemo demo = new SynchronizedDemo();

        //开启三个线程
        Thread t1 = new Thread(demo, "线程一");
        Thread t2 = new Thread(demo, "线程二");
        t1.start();
        Thread.sleep(100);
        demo.flag = false;
        t2.start();
    }
}
